package timing.ukulele.gateway.utils;

import timing.ukulele.common.Constant;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * jwt工具类
 */
public final class JWTUtil {

    private static Key getKeyInstance(String salt) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        String apiKey = DatatypeConverter.printBase64Binary(salt.getBytes());
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        return signingKey;
    }

    /**
     * 生成token
     *
     * @param claims
     * @return
     */
    public static String createJavaWebToken4JwtAuth(Map<String, Object> claims, String salt, Integer exp) {
        // 10小时
        String token = Jwts.builder().setClaims(claims).setExpiration(DateUtils.addSeconds(new Date(), exp))
                .signWith(SignatureAlgorithm.HS256, getKeyInstance(salt)).compact();
        return token;
    }

    /**
     * 获取body部分
     *
     * @param token
     * @return
     */
    public static Map<String, Object> verifyJavaWebToken(String token, String salt) {
        try {
            Map<String, Object> jwtClaims = Jwts.parser().setSigningKey(getKeyInstance(salt))
                    .parseClaimsJws(token).getBody();
            return jwtClaims;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Authentication getAuthentication(String token, String salt) {
        Map<String, Object> stringObjectMap = null;
        try {
            stringObjectMap = verifyJavaWebToken(token, salt);
        } catch (Exception ex) {
            return null;
        }
        if (stringObjectMap == null || stringObjectMap.get(Constant.USER_INFO) == null) {
            return null;
        }
        LinkedHashMap<String, Object> userDetails = (LinkedHashMap) stringObjectMap.get(Constant.USER_INFO);

        Collection<? extends GrantedAuthority> authorities = userDetails == null ? AuthorityUtils.NO_AUTHORITIES
                : AuthorityUtils.commaSeparatedStringToAuthorityList(String.valueOf(userDetails.get("role")));

        User principal = new User((String) userDetails.get("username"), "", authorities);

        return new UsernamePasswordAuthenticationToken(principal, token, authorities);
    }

    /**
     * 检验有效性
     *
     * @param token
     * @return
     */
    public static boolean isTokenEffect(String token, String salt) {
        if (StringUtils.isEmpty(token)) {
            return false;
        }
        Map<String, Object> claims = verifyJavaWebToken(token, salt);
        if (claims == null) {
            return false;
        }
        return true;
    }


}
